//
//  MPTLiveHomeVC.m
//  MPTLive
//
//  Created by HouGeng on 16/1/27.
//  Copyright © 2016年 Jeakin. All rights reserved.
//

#import "MPTLiveZuiXinVC.h"
#import "MPTLiveZuiXinCell.h"
#import "GuanZhuListVC.h"
#import "MPTHttpClient.h"
#import <MPTLivePlayerVC.h>
#import <MPTPlayerVC.h>
#import "FootRefreshView.h"
#import "HeadRefreshView.h"
#import "MeInfoMainVC.h"
#import <UIWindow+MPTWindow.h>
#import "MPTTips.h"
#import "MPTLiveViewController.h"
#import "LiveVC.h"
#import "MPTNoGuanZhuVIew.h"
#import <MPUmeng.h>

@interface MPTLiveZuiXinVC ()
<UITableViewDataSource,
UITableViewDelegate
>

@property (nonatomic, strong) UITableView *tableV;

@property (nonatomic, strong) NSMutableArray *maryListData;

/// 动画
@property (assign, nonatomic) CGPoint beginContentOffset;

/// 下一页的id
@property (nonatomic, strong) NSString *lastid;

/// 没有关注显示的view
@property (nonatomic, strong) MPTNoGuanZhuVIew *viewGuanZhu;


@property(nonatomic,retain) UIActivityIndicatorView *actView;

@end


@implementation MPTLiveZuiXinVC


#pragma mark - ********************** View Lifecycle **********************

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initVariable]; /// 初始化变量
    [self initViews]; /// 初始化界面
    
    [self req_URL_hot_live_channel]; /// 发送请求
    
    [self regNotification]; /// 注册消息
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[TPTabBarManager share] showBottomView:YES animation:YES];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    // 一定要关注这个函数是否被执行了！！！
}


#pragma mark - ********************** Init All Views **********************

- (void)initVariable
{
    self.maryListData = [NSMutableArray array];
}

- (void)initViews
{
    /// 初始化Nav导航栏
    [self initNavView];
}

- (void)initNavView
{
    [self initMainViews];
}

- (void)initMainViews
{
    if (!_tableV)
    {
        _tableV = [[UITableView alloc] initWithFrame:CGRectMake(0, -64, screenW, screenH) style:UITableViewStylePlain];
        _tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableV.showsHorizontalScrollIndicator = NO;
        _tableV.showsVerticalScrollIndicator = NO;
        _tableV.delegate = self;
        _tableV.dataSource = self;
        UIView *viewHead = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenW, TP_NavBar_H)];
        _tableV.tableHeaderView = viewHead;
        
        UIView *viewFoot = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenW, 49)];
        _tableV.tableFooterView = viewFoot;
        [self.view addSubview:_tableV];
        
        // 下拉刷新和上拉分页
        [_tableV addFootRefreshViewWithTarget:self advanceRefresh:YES action:@selector(fectchMoreData)];
        [_tableV.YX_FootRefreshView addCustomView:[FootRefreshView createFootRefresh]];
        
        [_tableV addHeadRefreshViewWithTarget:self action:@selector(fectchNewData)];
        [_tableV.YX_HeadRefreshView addCustomView:[HeadRefreshView createHeadRefreshShouYe]];
    }
}

- (void)initActView
{
    if (!self.actView)
    {
        //创建
        self.actView=[[UIActivityIndicatorView  alloc]initWithFrame:CGRectMake((screenW - 50)/ 2, (self.view.frame.size.height - 50) / 2 - 50, 50, 50)];
        
        //设置 风格;
        self.actView.activityIndicatorViewStyle= UIActivityIndicatorViewStyleGray;
        //设置活动指示器的颜色
        self.actView.color= RGBAColor(254, 222, 9, 1);
        //hidesWhenStopped默认为YES，会隐藏活动指示器。要改为NO
        self.actView.hidesWhenStopped=NO;
        //启动
        [self.actView startAnimating];
        
        [self.view addSubview:self.actView];
    }
    else
    {
        //停止
        [self.actView stopAnimating];
        self.actView.hidesWhenStopped=YES;
    }
}


#pragma mark - ********************** Functions **********************


#pragma mark - 导航栏 bar 动画
- (void)showNavAndFliterView:(BOOL)isShow
{
    [UIView animateWithDuration:0.25 animations:^{
        if (isShow)
        {
            [[TPTabBarManager share] showBottomView:YES animation:YES];
        }
        else
        {
            [[TPTabBarManager share] showBottomView:NO animation:YES];
        }
    }];
}


#pragma mark - 注册消息

- (void)regNotification
{
    /// 返回顶部的消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tablebviewToTop) name:@"tablebviewToTop" object:nil];
}

- (void)fectchNewData
{
    self.lastid = nil;
    [self req_URL_hot_live_channel];
}

- (void)fectchMoreData
{
    [self req_URL_hot_live_channel];
}


#pragma mark - ********************** Button Touch Event **********************


#pragma mark - ********************** Net Connection Event **********************

#pragma mark - 请求 xxx

- (void)req_URL_hot_live_channel
{
    if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        [MPTTips showSingleTips:@"网络好像有问题哦" duration:1.0f];
    }
    
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionaryWithObject:ZB_Str_Protect(_strType) forKey:@"type"];
    
    if (_lastid)
    {
        [paraDic setValue:_lastid forKey:@"lastid"];
    }
    else
    {
        [self initActView];
    }
    
    [[MPTHttpClient sharedMPHTTPClient] getPath:@"m/hot_live_channel.json" parameters:paraDic queuePriority:NSOperationQueuePriorityNormal cacheRequest:NO  success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [self initActView];
        
        if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            if ([responseObject[@"status"] integerValue] == 200)
            {
                if(self.lastid == nil)
                {
                    [self.maryListData removeAllObjects];
                }
                
                self.lastid = responseObject[@"lastid"];
                
                if ([responseObject[@"result"] isKindOfClass:[NSArray class]])
                {
                    [self.maryListData addObjectsFromArray:[self changDataToGirdValue:responseObject[@"result"]]];
                }
            }
            
            [self.tableV reloadData];
        }
        
        [self.tableV.YX_HeadRefreshView endRefreshing];
        if(self.lastid == nil || [@"" isEqualToString:self.lastid] || [@"null" isEqualToString:self.lastid]|| [@"nil" isEqualToString:self.lastid])
        {
            [self.tableV.YX_FootRefreshView noDataRefresh:YES];
        }
        else
        {
            [self.tableV.YX_FootRefreshView noDataRefresh:NO];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [self initActView];
        [self.tableV.YX_HeadRefreshView endRefreshing];
        [self.tableV.YX_FootRefreshView noDataRefresh:NO];
        
    } cached:nil];
}

/// 处理数据模型
- (NSMutableArray *)changDataToGirdValue:(NSMutableArray *)mary
{
    NSMutableArray *ary = [NSMutableArray arrayWithArray:mary];
    NSInteger hang = (ary.count%3==0)?(ary.count/3):(ary.count/3+1);
    NSMutableArray * aryGrid = [NSMutableArray array];
    NSMutableArray * aryTteam = [NSMutableArray array];
    
    for (int i=0; i<hang; i++)
    {
        if (i+1 < hang)
        {
            aryTteam = [NSMutableArray array];
            for (int i=0; i<3; i++)
            {
                [aryTteam addObject:[ary objectAtIndex:i]];
            }
            [aryGrid addObject:aryTteam];
            
            // 把添加过的删掉
            NSRange range = NSMakeRange(0,3);
            [ary removeObjectsInRange:range];
        }
        else if (i+1 == hang)
        {
            aryTteam = [NSMutableArray array];
            for (int i =0; i<ary.count; i++)
            {
                [aryTteam addObject:[ary objectAtIndex:i]];
            }
            [aryGrid addObject:aryTteam];
        }
    }
    return aryGrid;
}

#pragma mark - 处理 xxx

#pragma mark - ********************** Delegate Event **********************

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (screenW - 6) / 3 + 1.5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _maryListData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MPTLiveZuiXinCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MPTLiveZuiXinCell"];
    if (!cell)
    {
        cell = [[MPTLiveZuiXinCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MPTLiveZuiXinCell"];
    }
    
    cell.indexpath = indexPath;
    cell.aryData = _maryListData[indexPath.row];
    /// 点击头像的block
    [cell setBlock:^(NSIndexPath *indexpath , NSInteger intRow){
        [self presentVC:indexpath intRow:intRow];
        [MPUmeng event:@"TabHomePageClick" attributes:@{@"page":@"new"}];
    }];
    
    return cell;
}

- (void)presentVC:(NSIndexPath *)indexpath intRow:(NSInteger)intRow
{
    /// 获取选择行
    NSArray *ary = _maryListData[indexpath.row];
    
    /// 保护
    if (ary.count <= intRow)
    {
        return;
    }
    
    /// 获取数据
    NSDictionary *dic = ary[intRow][@"channel"];
    
    if (dic[@"scid"])
    {
        /// 视频中心类
        [[TPTabBarManager share] showBottomView:NO animation:YES];
        
        /// 视频状态
        if ([dic[@"liveStatus"] integerValue] == 1)
        {
            MPTLivePlayerVC *vc = [[MPTLivePlayerVC alloc] initWithScid:dic[@"scid"]];
            vc.strImageUrl = [NSString stringWithFormat:@"%@%@",dic[@"pic"][@"base"],dic[@"pic"][@"m"]];
            /// 获取视频的url
            if ([dic[@"liveUrls"] isKindOfClass:[NSArray class]])
            {
                if ([dic[@"liveUrls"] count] > 0)
                {
                    vc.strVideoUrl = [dic[@"liveUrls"] firstObject];
                }
            }
            [[UIApplication sharedApplication].keyWindow.visibleViewController presentViewController:vc animated:YES completion:nil];
        }
        else
        {
            MPTPlayerVC *vc = [[MPTPlayerVC alloc] initWithScid:dic[@"scid"]];
            vc.strImageUrl = [NSString stringWithFormat:@"%@%@",dic[@"pic"][@"base"],dic[@"pic"][@"m"]];
            /// 获取视频的url
            if ([dic[@"liveUrls"] isKindOfClass:[NSArray class]])
            {
                if ([dic[@"liveUrls"] count] > 0)
                {
                    vc.strVideoUrl = [dic[@"liveUrls"] firstObject];
                }
            }
            [[UIApplication sharedApplication].keyWindow.visibleViewController presentViewController:vc animated:YES completion:nil];
        }
    }
    else
    {
        
    }

}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.beginContentOffset = scrollView.contentOffset;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //TODO: 判断是否收起导航
    NSInteger originYOffSet = scrollView.contentOffset.y - self.beginContentOffset.y;
    //滑动超过10,为了表现同时隐藏导航和排序视图,必须偏移超过关联词视图出页面才可以执行隐藏导航.
    if (scrollView.contentOffset.y>105 && originYOffSet > 0)
    {
        //navgation隐藏的时候 对section的处理
        //section会延迟隐藏
        if ([scrollView isKindOfClass:[UITableView class]])
        {
            CGFloat sectionHeaderHeight = 45;
            if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0)
            {
                scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
            } else if (scrollView.contentOffset.y>=sectionHeaderHeight)
            {
                scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
            }
        }
        
        [self showNavAndFliterView:NO];
    }
    else if(originYOffSet < 0)
    {
        //navgation显示的时候 对section的处理
        if ([scrollView isKindOfClass:[UITableView class]])
        {
            CGFloat sectionHeaderHeight = 0;
            if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0)
            {
                scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
            } else if (scrollView.contentOffset.y>=sectionHeaderHeight)
            {
                scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
            }
        }
        
        [self showNavAndFliterView:YES];
    }
}

#pragma mark - ********************** Notification Event **********************


#pragma mark - 通知返回顶部的方法
- (void)tablebviewToTop
{
    if (self.tableV && _maryListData.count > 0)
    {
        [self.tableV setContentOffset:CGPointMake(0,0) animated:YES];
    }
}

@end
